package cn.amos.gateway.web;

import cn.amos.server.request.RegisterForm;
import cn.amos.server.response.LoginInfoVO;
import cn.amos.server.ws.service.WsLoginService;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;

/**
 * PROJECT: ws-gateway
 * DESCRIPTION: 登录相关接口
 *
 * @author amos.wang
 * @date 2019/4/12
 */
@Controller
@RequestMapping("login")
public class LoginController {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

    @Value("${ws.core.path}")
    private String serverBaseUrl;

    @Resource
    private WsLoginService wsLoginService;

    /**
     * 用户注册 1
     * 通过 application-cxf.xml 配置，获取 WsLoginService 实例
     *
     * @param phone 手机号
     * @return 用户注册信息
     */
    @RequestMapping("register/{phone}")
    @ResponseBody
    public String register(@PathVariable("phone") String phone) {
        RegisterForm registerForm = getRegisterForm(phone);

        LOGGER.info("XML配置方式 用户注册~~~");
        return wsLoginService.register(registerForm).toString();
    }

    /**
     * 用户注册 2
     * 通过代理配置，获取 WsLoginService 实例
     * http://localhost:8080/ws-server/ws/login?wsdl
     *
     * @param phone 手机号
     * @return 用户注册信息
     */
    @RequestMapping("register2/{phone}")
    @ResponseBody
    public String register2(@PathVariable("phone") String phone) {
        // JaxWsProxyFactoryBean 创建客户端的代理，生成factory对象，用于调用服务端的方法
        JaxWsProxyFactoryBean soapFactoryBean = new JaxWsProxyFactoryBean();
        soapFactoryBean.setAddress(serverBaseUrl + "ws/login");
        soapFactoryBean.setServiceClass(WsLoginService.class);
        WsLoginService service = (WsLoginService) soapFactoryBean.create();

        LOGGER.info("客户端代理方式 用户注册~~~");
        LoginInfoVO register = service.register(getRegisterForm(phone));

        return register.toString();
    }

    /**
     * 模拟生产用户注册信息
     *
     * @param phone 手机号
     * @return RegisterForm
     */
    private RegisterForm getRegisterForm(String phone) {
        RegisterForm registerForm = new RegisterForm();
        registerForm.setPhoneNo(phone);
        registerForm.setPassword("666666");
        registerForm.setCreateTime(new Date());
        registerForm.setChannel(RandomUtils.nextBoolean() ? "APP" : "WEB");
        registerForm.setUsername((RandomUtils.nextBoolean() ? "AMOS" : "LUCY") + (RandomUtils.nextInt(50) + 10));
        return registerForm;
    }

}
